const ejs = require('ejs');
const _ = require("lodash");
const fs = require("fs");
const path = require("path");
const phantom = require('phantom');

const layoutHtmlStr = fs.readFileSync(path.resolve(__dirname, `../template/echarts.ejs`), 'utf-8')

async function renderUrlChart(req, res, next) {
  const url = req.query.url

  const pngBase64 = await htmlToBase64Img(url)
  res.send({
    imgBase64: "data:image/jpeg;base64," + pngBase64,
    openUrl: url
  })

}

async function htmlToBase64Img(targetUrl, viewportSize) {
  return new Promise(async (resolve, reject) => {
    const instance = await phantom.create();
    const page = await instance.createPage();
    await page.open(targetUrl);
    await page.property('content');
    const base64 = await page.renderBase64('PNG')
    console.log(2222, +new Date(), base64)
    page.close();
    instance.exit();
    resolve(base64)
  })
}

async function renderChart(req, res, next) {

  let chartConfig = req.body.chartConfig
  let name = req.body.name;
  let chartWidth = Number(req.body.width);
  let chartHeight = Number(req.body.height);

  const htmlDistPath = path.resolve(__dirname, "../static/html")

  chartWidth = chartWidth || 800;
  chartHeight = chartHeight || 400;
  const clipRect = {top: 0, left: 0, width: chartWidth, height: chartHeight};

  const filename = (name || "").toString() +
    (+new Date()).toString() + "-" + parseInt(Math.random() * 1000000).toString() + ".html"


  let filePath = path.join(htmlDistPath, `${filename}`);

  let html = ejs.render(layoutHtmlStr, {
    chartConfigStr: JSON.stringify(chartConfig || {}),
    chartWidth,
    chartHeight,
  })

  try {
    await fs.writeFileSync(filePath, html)
    const openUrl = req.protocol + "://" + req.get('host') + "/html/" + filename
    console.log(clipRect)
    const pngBase64 = await htmlToBase64Img(openUrl, clipRect)
    res.send({
      imgBase64: "data:image/jpeg;base64," + pngBase64,
      openUrl
    })
  } catch (e) {
    next(e)
  }
}

module.exports = {
  renderChart, renderUrlChart
}
